package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.feedback.FeedbackAddRequest;
import com.SmartCampus.system.model.dto.feedback.FeedbackQueryRequest;
import com.SmartCampus.system.model.dto.feedback.FeedbackResponseRequest;
import com.SmartCampus.system.model.dto.feedback.FeedbackUpdateRequest;
import com.SmartCampus.system.model.entity.Feedback;
import com.SmartCampus.system.model.entity.User;
import com.SmartCampus.system.model.vo.FeedbackVO;
import com.SmartCampus.system.service.FeedbackService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 反馈接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/feedback")
@Slf4j
@Api(tags = "反馈接口")
public class FeedbackController {

    @Resource
    private FeedbackService feedbackService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建反馈（仅管理员）
     *
     * @param feedbackAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建反馈")
    public BaseResponse<Long> addFeedback(@RequestBody FeedbackAddRequest feedbackAddRequest, HttpServletRequest request) {
        if (feedbackAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userService.getLoginUser(request).getId();
        Feedback feedback = new Feedback();
        BeanUtils.copyProperties(feedbackAddRequest, feedback);
        feedback.setUserId(userId);
        boolean result = feedbackService.save(feedback);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(feedback.getId());
    }

    /**
     * 删除反馈（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除反馈（仅管理员）")
    public BaseResponse<Boolean> deleteFeedback(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = feedbackService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新反馈（仅管理员）
     *
     * @param feedbackUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新反馈（仅管理员）")
    public BaseResponse<Boolean> updateFeedback(@RequestBody FeedbackUpdateRequest feedbackUpdateRequest, HttpServletRequest request) {
        if (feedbackUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        userService.getLoginUser(request).getUsername();
        QueryWrapper<User> queryUser = new QueryWrapper<>();
        QueryWrapper<Feedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", feedbackUpdateRequest.getId());
        Feedback feedback = feedbackService.getOne(queryWrapper);
        if (feedbackUpdateRequest.getName() == null || feedbackUpdateRequest.getName().equals("")) {
            feedback.setUserId(feedback.getUserId());
        } else {
            queryUser.eq("username", feedbackUpdateRequest.getName());
            feedback.setUserId(userService.getOne(queryUser).getId());
        }
        if (feedbackUpdateRequest.getContent() == null || feedbackUpdateRequest.getContent().equals("")) {
            feedbackUpdateRequest.setContent(feedback.getContent());
        }
        if (feedbackUpdateRequest.getFeedbackType() == null || feedbackUpdateRequest.getFeedbackType().equals("")) {
            feedbackUpdateRequest.setFeedbackType((String) feedback.getFeedbackType());
        }
        if (feedbackUpdateRequest.getReply() == null || feedbackUpdateRequest.getReply().equals("")) {
            feedbackUpdateRequest.setReply(feedback.getReply());
        }
        BeanUtils.copyProperties(feedbackUpdateRequest, feedback);
        boolean result = feedbackService.updateById(feedback);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 回复反馈（仅管理员）
     *
     * @param feedbackResponseRequest
     * @return
     */
    @PostMapping("/respond")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "回复反馈（仅管理员）")
    public BaseResponse<Boolean> responseFeedback(@RequestBody FeedbackResponseRequest feedbackResponseRequest) {
        if (feedbackResponseRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        QueryWrapper<Feedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", feedbackResponseRequest.getId());
        Feedback feedback = feedbackService.getOne(queryWrapper);
        BeanUtils.copyProperties(feedbackResponseRequest, feedback);
        boolean result = feedbackService.updateById(feedback);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }


    /**
     * 分页获取反馈列表（仅管理员）
     *
     * @param feedbackQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取反馈列表（仅管理员）")
    public BaseResponse<Page<FeedbackVO>> getFeedbackByAll(@RequestBody FeedbackQueryRequest feedbackQueryRequest) {
        long current = feedbackQueryRequest.getCurrent() == 0 ? 1 : feedbackQueryRequest.getCurrent();
        long size = feedbackQueryRequest.getPageSize() == 0 ? 10 : feedbackQueryRequest.getPageSize();
        Page<FeedbackVO> page = new Page<>(current, size);
        Page<FeedbackVO> feedbackPage = feedbackService.getFeedbackByAll(page, feedbackQueryRequest);
        if (feedbackPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(feedbackPage);
    }

    /**
     * 分页获取用户反馈列表
     *
     * @param feedbackQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/my")
    @ApiOperation(value = "分页获取用户反馈列表")
    public BaseResponse<Page<FeedbackVO>> getFeedbackByMy(@RequestBody FeedbackQueryRequest feedbackQueryRequest, HttpServletRequest request) {
        if (feedbackQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userService.getLoginUser(request).getId();
        long current = feedbackQueryRequest.getCurrent() == 0 ? 1 : feedbackQueryRequest.getCurrent();
        long size = feedbackQueryRequest.getPageSize() == 0 ? 10 : feedbackQueryRequest.getPageSize();

        Page<FeedbackVO> page = new Page<>(current, size);
        Page<FeedbackVO> feedbackPage = feedbackService.getFeedbackByMy(page, feedbackQueryRequest, userId);
        if (feedbackPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(feedbackPage);
    }

    // endregion
}
